/**
 * Copyright 2009 University of Washington This code is released under the GPL version 3 - with a copy of the license
 * included
 * 
 * @author Maya Hao Li
 */
package seedpod.webapp.view.seedpodwidgets;

/**
 * Drop down selections. It doesn't support selecting multiple values
 */
import seedpod.exceptions.InvalidWidgetException;
import seedpod.model.AVPair;
import seedpod.model.ProtegeValueType;
import seedpod.model.SeedpodModel.RdbCls.FormWidget;
import seedpod.model.SeedpodModel.RdbCls.ViewWidget;
import seedpod.model.rdb.MetaRdbSlot;
import seedpod.model.rdb.RdbValueType;
import seedpod.webapp.view.htmlwidget.SelectInput;

public class Select extends LimsWidget {

	protected String[] _symbols;
	private String _symbolValue = "";

	public Select() {
	// TODO Auto-generated constructor stub
	}

	public Select(AVPair avpair) {
		super( avpair );
		initSelectionCollection();
	}

	@Override
	public FormWidget getFormWidgetType() {
		return FormWidget.SELECT;
	}

	private int getSymbolIndex() {
		if ( _symbolValue == null || _symbolValue == "" ) return 0;

		for ( int i = 0; i < _symbols.length; i++ )
			if ( _symbolValue.compareTo( _symbols[i] ) == 0 ) return i;
		return 0;
	}

	@Override
	public ViewWidget getViewWidgetType() {
		return null;
	}

	protected void initSelectionCollection() {
		String allSymbols = getAttribute().getAllowedValues();
		if ( allSymbols != null )
			_symbols = allSymbols.split( MetaRdbSlot.VALUE_DELIMITER );
		else {
			_symbols = new String[1];
			_symbols[0] = "<no selection choices>";
		}
	}

	@Override
	public String render() {
		SelectInput seInput = new SelectInput( _widgetID, _symbolValue, _symbols );
		seInput.setSelectedIndex( getSymbolIndex() );
		return seInput.render();
	}

	@Override
	public void setData( Object data ) {
		_symbolValue = data == null ? "" : (String)data;
	}

	@Override
	public void validateWidget() throws InvalidWidgetException {
		if ( getAttribute().getRdbValueType() != RdbValueType.VARCHAR || !getAttribute().getProtegeValueType().equals(
				ProtegeValueType.Symbol ) )
			throw new InvalidWidgetException( "Select widget uses data of string type or symbols only. " );
	}

}